/*
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author         Notes
 * 2021-10-12     heyuanjie87    1st version
 */

#include <rtthread.h>
#include <rtdevice.h>

#include <dfs_posix.h>
#include <dfs_poll.h>

#include <usdev/i2c-dev.h>

static int _fops_open(struct dfs_fd *fd, ...)
{
    int ret = 0;

    return ret;
}

static int _fops_close(struct dfs_fd *fd)
{
    int ret;

    return ret;
}

static int _fops_ioctl(struct dfs_fd *fd, int cmd, void *args)
{
    int ret = -1;
    struct rt_i2c_bus_device *bus = (struct rt_i2c_bus_device *)fd->data;

    switch (cmd)
    {
    case I2C_RDWR:
    {
        struct i2c_rdwr_ioctl_data *req = (struct i2c_rdwr_ioctl_data *)args;

        ret = rt_i2c_transfer(bus, req->msgs, req->nmsgs);
        if (ret != req->nmsgs)
            ret = -EIO;
        else
            ret = 0;
    }
    break;
    }

    return ret;
}

static int _fops_read(struct dfs_fd *file, void *buf, size_t size, ...)
{

    return 0;
}

static int _fops_write(struct dfs_fd *file, const void *buf, size_t size, ...)
{
    return 0;
}

static const struct dfs_file_ops _i2c_fops = {
    _fops_open,
    _fops_close,
    _fops_ioctl,
    _fops_read,
    _fops_write,
    RT_NULL, /* flush */
    RT_NULL, /* lseek */
    RT_NULL, /* getdents */
    RT_NULL,
};

rt_err_t rt_i2c_bus_device_device_init(struct rt_i2c_bus_device *bus,
                                       const char *name)
{
    struct rt_device *device;
    RT_ASSERT(bus != RT_NULL);

    device = &bus->parent;

    device->user_data = bus;

    /* set device type */
    device->type = RT_Device_Class_I2CBUS;

    /* register to device manager */
    rt_device_register(device, name, RT_DEVICE_FLAG_RDWR);

    device->fops = &_i2c_fops;

    return RT_EOK;
}
